import java.util.*;

public class FindFrequentTreeSum {

    HashMap<Integer, Integer> map = new HashMap<>();
    int max = 0;
    public int[] findFrequentTreeSum(TreeNode root) {
        int temp = process(root);
        map.put(temp, map.getOrDefault(temp, 0) + 1);
        max = Math.max(max, map.get(temp));
        ArrayList<Integer> list = new ArrayList<>();
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            if (entry.getValue() == max) list.add(entry.getKey());
        }
        int[] ans = new int[list.size()];
        for (int i = 0; i < list.size(); i++) {
            ans[i] = list.get(i);
        }
        return ans;
    }

    public int process(TreeNode node) {
        if (node == null) return 0;
        int l = process(node.left);
        int r = process(node.right);
        if (node.left != null) {
            map.put(l, map.getOrDefault(l, 0) + 1);
            max = Math.max(max, map.get(l));
        }
        if (node.right != null) {
            map.put(r, map.getOrDefault(r, 0) + 1);
            max = Math.max(max, map.get(r));
        }
        return l + r + node.val;
    }
}
